//
//  AVPlayController.m
//  BeautyClother
//
//  Created by dllo on 15/9/30.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "AVPlayController.h"
#import "AsyncConnection.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "UIButton+WebCache.h"
#import "OneUserCell.h"
#import "TwoUserCell.h"
#import "UIImageView+WebCache.h"
#import "ThreeProCell.h"
#import "FourMovieCell.h"
#import "PlayView.h"
#import "HederView.h"
@interface AVPlayController ()<UITableViewDataSource, UITableViewDelegate>

{
    BOOL _played;
    NSString *_totalTime;
    NSDateFormatter *_dateFormatter;
}

@property (nonatomic, retain) NSMutableArray *productList;

@property (nonatomic, retain) NSMutableArray *relatedVideoList;

@property (nonatomic, retain) NSMutableDictionary *dic;

@property (nonatomic, retain) UITableView *table;

@property (nonatomic, retain) MPMoviePlayerViewController *moviePlayer;

@property (nonatomic, retain) HederView *headerView;

@property (nonatomic, retain) NSString *video;
@end

@implementation AVPlayController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.productList = [NSMutableArray array];
        self.relatedVideoList = [NSMutableArray array];
        self.dic = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)handleData
{
    [AsyncConnection asyncConnection:[NSString stringWithFormat:@"http://v.meilapp.com:8080%@", self.url] parmaters:nil block:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.dic = [result objectForKey:@"detail"];
        NSArray *array = [result objectForKey:@"productList"];
        [self.productList addObjectsFromArray:array];
    self.video = [self.dic objectForKey:@"video_url"];
//        [self videoValueWithURL:[self.dic objectForKey:@"video_url"]];
        NSArray *arr = [result objectForKey:@"relatedVideoList"];
        [self.relatedVideoList addObjectsFromArray:arr];
        [self.table reloadData];
    } path:@"AVPLayer"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    [self createTable];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:_table];
    self.table.delegate = self;
    self.table.dataSource = self;
    [_table release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return self.productList.count;
    }if (section == 3) {
        if (self.relatedVideoList.count %  2 == 0) {
            return self.relatedVideoList.count / 2;
        }
        else{
        return self.relatedVideoList.count / 2 + 1;
        }
    } else
    {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OneUserCell *one = [tableView dequeueReusableCellWithIdentifier:@"one"];
        if (!one) {
            one = [[OneUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"one"];
        }
        one.title.text = [self.dic objectForKey:@"title"];
        [one.addtime setImage:[UIImage imageNamed:@"date.png"] forState:UIControlStateNormal];
        [one.addtime setTitle:[self.dic objectForKey:@"addtime"] forState:UIControlStateNormal];
        [one.addtime setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        
        [one.tagList setTitle:[[[self.dic objectForKey:@"tagList"] objectAtIndex:0] objectForKey:@"tag_name"] forState:UIControlStateNormal];
        [one.tagList setTitleColor:[UIColor colorWithRed:255 / 255 green:0 / 255 blue:255 / 255 alpha:1] forState:UIControlStateNormal];
        return one;
    }if (indexPath.section == 1) {
        TwoUserCell *two = [tableView dequeueReusableCellWithIdentifier:@"two"];
        if (!two) {
            two = [[TwoUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"two"];
        }
        
        if ([[self.dic objectForKey:@"introduction"] isEqualToString:@""]) {
            two.intro.frame = CGRectMake(0, 0, 0, 0);
        } else{
            CGFloat offheight = [UIScreen mainScreen].bounds.size.height / 667;
            two.intro.frame = CGRectMake(5, 5, two.contentView.frame.size.width - 10, 100 * offheight);
            two.intro.numberOfLines = 2;
        two.intro.text = [self.dic objectForKey:@"introduction"];
        }
        
        NSString *string = [NSString stringWithFormat:@"http://v.meilapp.com:8080%@",[self.dic objectForKey:@"image_url"]];
        [two.image sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        NSString *str = [NSString stringWithFormat:@"http://v.meilapp.com:8080%@", [self.dic objectForKey:@"avatar"]];
        [two.avatar sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        two.username.text = [self.dic objectForKey:@"username"];
        two.signature.text = [self.dic objectForKey:@"signature"];
        return two;
    }
    if (indexPath.section == 2) {
        ThreeProCell *three = [tableView dequeueReusableCellWithIdentifier:@"three"];
        if (!three) {
            three = [[ThreeProCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"three"];
        }
        [three.image sd_setImageWithURL:[NSURL URLWithString:[[self.productList objectAtIndex:indexPath.row] objectForKey:@"small_image_url"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        three.name.text = [[self.productList objectAtIndex:indexPath.row] objectForKey:@"title"];
        three.intro.text = [NSString stringWithFormat:@"%@", [[self.productList objectAtIndex:indexPath.row] objectForKey:@"price"]];
        three.selectionStyle = UITableViewCellSelectionStyleNone;
        return three;
    }
    
    else{
        FourMovieCell *four = [tableView dequeueReusableCellWithIdentifier:@"four"];
        if (!four) {
            four = [[FourMovieCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"four"];
        }
        NSString *string1 = [NSString stringWithFormat:@"http://v.meilapp.com:8080%@", [[self.relatedVideoList objectAtIndex:indexPath.row * 2] objectForKey:@"image_url"]];
        [four.image1 sd_setImageWithURL:[NSURL URLWithString:string1] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        four.selectionStyle =  UITableViewCellSelectionStyleNone;
        four.title1.text = [[self.relatedVideoList objectAtIndex:indexPath.row * 2] objectForKey:@"title"];
        
        
        if (self.relatedVideoList.count / 2 != indexPath.row) {
            NSString *string2 = [NSString stringWithFormat:@"http://v.meilapp.com:8080%@", [[self.relatedVideoList objectAtIndex:indexPath.row * 2 + 1] objectForKey:@"image_url"]];
            [four.image2 sd_setImageWithURL:[NSURL URLWithString:string2] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            four.title2.text = [[self.relatedVideoList objectAtIndex:indexPath.row * 2 + 1] objectForKey:@"title"];
            
        }

        
        four.image1.userInteractionEnabled = YES;
        four.image2.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        
        [four.image1 addGestureRecognizer:tap1];
        [four.image2 addGestureRecognizer:tap2];
        
        four.image1.tag = indexPath.row * 2;
        four.image2.tag = indexPath.row * 2 + 1;
        
        
        return four;
    }
}

- (void)tap:(UITapGestureRecognizer *)tap
{
    AVPlayController *avplay = [[AVPlayController alloc] init];
     NSString *string = [NSString stringWithFormat:@"%@", [[self.relatedVideoList objectAtIndex:tap.view.tag] objectForKey:@"url"]];
    avplay.url = string;
    [self.navigationController pushViewController:avplay animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat offheight = [UIScreen mainScreen].bounds.size.height / 667;
    if (indexPath.section == 0) {
        return 100 * offheight;
    }
    if (indexPath.section == 1) {
        if ([[self.dic objectForKey:@"introduction"] isEqualToString:@""]) {
            return 300 * offheight;
        } else
        {
        return 400 * offheight;
        }
    }
    if (indexPath.section == 2) {
        return 100 * offheight;
    }
    else
    {
        return 200 * offheight;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return @"简介";
    }
    if (section == 2) {
        return @"提及产品";
    }
    if (section == 3) {
        return @"相关视频";
    } else
    {
        return nil;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        self.headerView = [tableView dequeueReusableCellWithIdentifier:self.video];
        if (self.headerView == nil) {
            self.headerView = [[HederView alloc]initWithReuseIdentifier:self.video];
            [_headerView passDic:self.video];
            
        }
        return _headerView;
    }else
    {
        return [[[UITableViewHeaderFooterView alloc]init]autorelease];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat offheight = [UIScreen mainScreen].bounds.size.height / 667;
    if (section == 0) {
        return 300 * offheight;
    } else
    {
        return 40 * offheight;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
